package cee

import (
	"strings"
)

type node struct {
	pattern  string
	part     string
	children []*node
	isWild   bool
}

// 路由节点插入
func (n *node) insert(path string, parts []string, level int) {
	if level == len(parts) {
		n.pattern = path
		return
	}
	part := parts[level]

	chi := n.matchChild(part)

	if chi == nil {
		chi = &node{part: parts[level], isWild: part[0] == ':' || part[0] == '*'}
		n.children = append(n.children, chi)
	}

	chi.insert(path, parts, level+1)
}

// 匹配路由 用于插入
func (n *node) matchChild(part string) *node {
	for _, chi := range n.children {
		if chi.part == part || chi.isWild {
			return chi
		}
	}

	return nil
}

// 匹配节点 用于查找
func (n *node) matchChildren(part string) []*node {
	nodes := make([]*node, 0)

	for _, child := range n.children {
		if child.part == part || child.isWild {
			nodes = append(nodes, child)
		}
	}
	return nodes
}

// 查找路由
func (n *node) search(parts []string, level int) *node {
	if len(parts) == level || strings.HasPrefix(n.part, "*") {
		if n.pattern == "" {
			return nil
		}
		return n
	}

	part := parts[level]
	chi := n.matchChildren(part)

	for _, v := range chi {
		result := v.search(parts, level+1)

		if result != nil {
			return result
		}
	}

	return nil
}
